package com.itisyue.fun.advice;

import com.alibaba.fastjson.JSONObject;
import com.itisyue.fun.dto.BusinessException;
import com.itisyue.fun.dto.ErrorCode;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
public class RestExceptionHandler {
    Logger log = LoggerFactory.getLogger(RestExceptionHandler.class);

    /**
     * 自定义参数校验失败
     * @param ex
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public RestResult processValidationError(ConstraintViolationException ex){
        log.error("ExceptionTranslator ConstraintViolationException:",ex);
        return ResultUtil.fail(ErrorCode.ERR_VALIDATION.getValue(), ex.getMessage());
    }

    /**
     * body参数校验失败
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public RestResult processValidationError(MethodArgumentNotValidException ex){
        log.error("ExceptionTranslator MethodArgumentNotValidException:",ex);
        BindingResult bindingResult = ex.getBindingResult();
        return processBindingResult(bindingResult);
    }
    private RestResult processBindingResult(BindingResult result){
        List<ObjectError> allErrors = result.getAllErrors();
        RestResult restResult = new RestResult();
        restResult.setCode(ErrorCode.ERR_VALIDATION.getValue());
        restResult.setMsg(ErrorCode.ERR_VALIDATION.getDesc());
        if(CollectionUtils.isNotEmpty(allErrors)){
            List<String> errorMsgs = allErrors.stream().map(error ->
                    error.getDefaultMessage())
                    .collect(Collectors.toList());
            log.warn(JSONObject.toJSONString(errorMsgs));
            String message = errorMsgs.stream().collect(Collectors.joining(";"));
            restResult.setMsg(message);
        }
        return restResult;
    }

    /**
     * http method有误
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ResponseBody
    public RestResult httpRequestMethodNotSupportedException(MethodArgumentNotValidException ex){
        log.error("ExceptionTranslator HttpRequestMethodNotSupportedException:",ex);
        return ResultUtil.fail(ErrorCode.METHOD_NOT_SUPPORTED.getValue(), ex.getMessage());
    }

    /**
     * 未传requestBody
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public RestResult httpMessageNotReadableException(HttpMessageNotReadableException ex){
        log.error("ExceptionTranslator httpMessageNotReadableException:",ex);
        return ResultUtil.fail("HttpMessageNotReadableException");
    }

    /**
     * 自定义异常捕获
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public RestResult businessException(BusinessException ex){
        log.error("ExceptionTranslator 业务异常:",ex);
        ErrorCode code = ex.getCode();
        return ResultUtil.fail(code.getDesc());
    }
    /**
     * 普通异常捕获
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResult exception(Exception ex){
        log.error("ExceptionTranslator 系统内部错误:",ex);
        return ResultUtil.fail(ErrorCode.INTERNAL_SERVER_ERROR.getDesc());
    }
}
